import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import {
  Carousel,
  Rate,
  Tag,
  Button,
  Divider,
  Image,
  Typography,
  Row,
  Col,
  Card,
  Statistic,
  message,
  Avatar,
  Empty,
} from "antd";
import {
  DownloadOutlined,
  TeamOutlined,
  ClockCircleOutlined,
  StarOutlined,
  UserOutlined,
  MessageOutlined,
  StarFilled,
  ShoppingCartOutlined,
  PlusSquareOutlined,
} from "@ant-design/icons";
import style from "./index.module.css";
import { getGameInfoApi } from "@/apis/game";
import CommentButton from "@/components/comment";
import { addGameCommentApi } from "@/apis/client";
import { getGameCommentListApi } from "@/apis/comment";
import timeAgo from "@/utils/timeAge";
import { addGoods } from "@/store/modules/cratStore";
import { useDispatch, useSelector } from "react-redux";
import { addGoodsApi } from "@/apis/cart";

const { Title, Paragraph, Text } = Typography;

export default function GameInfo() {
  const { id } = useParams();
  const { cart } = useSelector((state: any) => state.cart);
  const dispatch = useDispatch();
  const profile = useSelector((state: any) => state.user.profile);
  const [isFavorite, setIsFavorite] = useState(false);
  const [game, setGame] = useState({
    id: 1,
    title: "赛博朋克 2077",
    coverImage:
      "http://localhost:9000/tempfilebucket/8b47aa8de19b47368faa014eb87bbf1a.jpg",
    developer: "CD Projekt Red",
    publisher: "CD Projekt",
    releaseDate: "2020-12-10",
    genre: ["RPG", "开放世界", "第一人称射击"],
    rating: 4.5,
    ratingCount: 12500,
    description: `《赛博朋克 2077》是一款开放世界动作冒险 RPG 游戏。故事发生在夜之城，权力更迭和身体改造是这里不变的主题。您扮演一名野心勃勃的雇佣兵：V，正在追寻一种独一无二的植入体——获得永生的关键。自定义角色义体、技能和玩法，探索包罗万象的城市。您做出的选择也将会对剧情和周遭世界产生影响。`,
    gameInfo: {
      systemRequirements: {
        minimum: {
          os: "Windows 7 or 10 (64-bit)",
          processor: "Intel Core i5-3570K or AMD FX-8310",
          memory: "8 GB RAM",
          graphics: "NVIDIA GeForce GTX 780 or AMD Radeon RX 470",
          storage: "70 GB available space",
        },
        recommended: {
          os: "Windows 10 (64-bit)",
          processor: "Intel Core i7-4790 or AMD Ryzen 3 3200G",
          memory: "12 GB RAM",
          graphics: "GTX 1060 6GB / GTX 1660 Super or Radeon RX 590",
          storage: "70 GB available space (SSD recommended)",
        },
      },
      displayImages: [
        "http://localhost:9000/tempfilebucket/8b47aa8de19b47368faa014eb87bbf1a.jpg",
        "http://localhost:9000/tempfilebucket/8b47aa8de19b47368faa014eb87bbf1a.jpg",
        "http://localhost:9000/tempfilebucket/8b47aa8de19b47368faa014eb87bbf1a.jpg",
        "http://localhost:9000/tempfilebucket/8b47aa8de19b47368faa014eb87bbf1a.jpg",
      ],
      displayVideos: [],
    },
    price: 298,
    discount: 20,
    platforms: ["PC", "PlayStation", "Xbox"],
    multiplayer: true,
    averagePlaytime: 25,
  });

  const [comment, setComment] = useState("");
  const [commentCount, setCommentCount] = useState(0);
  const [comments, setComments] = useState([]);
  const [rate, setRate] = useState(0);

  async function addGameUserReview(content: string) {
    const gameComment = {
      userId: profile.id,
      gameId: id,
      rating: rate,
      comment: content,
    };
    try {
      const res: any = await addGameCommentApi(gameComment);
      if (res.code === 0) {
        setCommentCount(commentCount + 1);
        setComment("");
        setRate(0);
        message.success("评论成功");
        getGameComments(id);
      } else {
        message.error("评论失败");
      }
    } catch (error) {
      console.error("请求失败");
    }
  }

  const discountedPrice = game.price * (1 - game.discount / 100);

  const toggleFavorite = () => {
    setIsFavorite(!isFavorite);
  };

  async function getGameInfo(id: any) {
    try {
      const res: any = await getGameInfoApi(id);
      if (res.code === 0) {
        setGame(Object.assign(game, res.data));
      }
    } catch (error) {
      console.error("获取游戏信息失败:", error);
    }
  }

  async function getGameComments(id: any) {
    try {
      const res: any = await getGameCommentListApi({ page: 1, size: 10 }, id);
      if (res.code === 0) {
        setCommentCount(res.data.total);
        setComments(res.data.records);
      }
    } catch (error) {
      console.error("获取游戏评论失败:", error);
    }
  }

  async function addToGoods() {
    if (cart.some((item: any) => item.id === game.id)) {
      message.error("该商品已在购物车中");
      return;
    }

    const formData = new FormData();
    formData.append("gameId", game.id as any);

    try {
      const res: any = await addGoodsApi(formData);
      if (res.code === 0) {
        message.success("加入购物车成功");
        dispatch(addGoods(game));
      } else {
        message.error("加入购物车失败");
      }
    } catch (error) {
      message.error("请求失败");
    }
  }

  useEffect(() => {
    getGameInfo(id);
    getGameComments(id);
  }, [id]);

  return (
    <div className={style.gameInfoContainer}>
      {/* Game Header Section */}
      <Row gutter={24} className={style.gameHeader}>
        <Col xs={24} md={8} lg={6}>
          <div className={style.gameCover}>
            <Image src={game.coverImage} alt={game.title} preview={false} />
          </div>

          <div className={style.gameActions}>
            <Button
              type="primary"
              icon={<PlusSquareOutlined />}
              size="large"
              block
            >
              立即入库
            </Button>
            <Button
              style={{ marginTop: "1em" }}
              icon={<ShoppingCartOutlined />}
              size="large"
              block
              onClick={addToGoods}
            >
              加入购物车
            </Button>
          </div>
        </Col>

        <Col xs={24} md={16} lg={18}>
          <div className={style.gameMeta}>
            <Title level={2}>{game.title}</Title>

            <div className={style.gameRating}>
              <Rate
                allowHalf
                defaultValue={game.rating}
                disabled
                character={<StarOutlined />}
              />
              <Text type="secondary">
                {game.rating} ({(game.ratingCount || 0).toLocaleString()} 评价)
              </Text>
            </div>

            <Paragraph>
              <Text strong>开发商: </Text>
              <Text>{game.developer}</Text>
            </Paragraph>

            <Paragraph>
              <Text strong>发行商: </Text>
              <Text>{game.publisher}</Text>
            </Paragraph>

            <Paragraph>
              <Text strong>发行日期: </Text>
              <Text>{game.releaseDate}</Text>
            </Paragraph>

            <div className={style.gameTags}>
              {game.genre?.map((genre, index) => (
                <Tag key={index} color="geekblue">
                  {genre}
                </Tag>
              ))}
            </div>

            <Divider />

            <Row gutter={16} className={style.gameStats}>
              <Col span={8}>
                <Card size="small">
                  <Statistic
                    title="平均游戏时长"
                    value={game.averagePlaytime}
                    prefix={<ClockCircleOutlined />}
                    suffix="小时"
                  />
                </Card>
              </Col>
              <Col span={8}>
                <Card size="small">
                  <Statistic
                    title="支持平台"
                    value={game.platforms?.length || 0}
                    prefix={<DownloadOutlined />}
                  />
                </Card>
              </Col>
              <Col span={8}>
                <Card size="small">
                  <Statistic
                    title="多人游戏"
                    value={game.multiplayer ? "支持" : "不支持"}
                    prefix={<TeamOutlined />}
                  />
                </Card>
              </Col>
            </Row>
          </div>
        </Col>
      </Row>

      {/* Pricing Section */}
      <div className={style.gamePricing}>
        <div className={style.originalPrice}>
          <Text delete>¥{game.price}</Text>
        </div>
        <div className={style.discountedPrice}>
          <Title level={3} style={{ margin: 0 }}>
            ¥{discountedPrice.toFixed(2)}
          </Title>
          <Tag color="red">{game.discount}% 折扣</Tag>
        </div>
      </div>

      {/* Vertical Content Sections */}
      <div className={style.verticalContent}>
        {/* Game Description Section */}
        <section className={style.contentSection}>
          <Title level={3} className={style.sectionTitle}>
            游戏介绍
          </Title>
          <Paragraph>{game.description}</Paragraph>

          {game.gameInfo?.displayImages?.length > 0 && (
            <>
              <Title level={4}>游戏截图</Title>
              <Carousel autoplay dots={{ className: style.displayImages }}>
                {game.gameInfo.displayImages.map((image, index) => (
                  <div key={index}>
                    <Image
                      src={image}
                      alt={`${game.title} 截图 ${index + 1}`}
                      preview={{ mask: "查看大图" }}
                    />
                  </div>
                ))}
              </Carousel>
            </>
          )}
        </section>

        <Divider />

        {/* System Requirements Section */}
        <section className={style.contentSection}>
          <Title level={3} className={style.sectionTitle}>
            系统需求
          </Title>

          <section className={style.systemRequirementsContainer}>
            {game.gameInfo?.systemRequirements?.minimum && (
              <section style={{ flex: 1 }}>
                <Title level={4}>最低配置</Title>
                <ul className={style.systemRequirements}>
                  {Object.entries(game.gameInfo.systemRequirements.minimum).map(
                    ([key, value]) => (
                      <li key={key}>
                        <Text strong>{key}: </Text>
                        <Text>{value}</Text>
                      </li>
                    )
                  )}
                </ul>
              </section>
            )}

            {game.gameInfo?.systemRequirements?.recommended && (
              <section style={{ flex: 1 }}>
                <Title level={4}>推荐配置</Title>
                <ul className={style.systemRequirements}>
                  {Object.entries(
                    game.gameInfo.systemRequirements.recommended
                  ).map(([key, value]) => (
                    <li key={key}>
                      <Text strong>{key}: </Text>
                      <Text>{value}</Text>
                    </li>
                  ))}
                </ul>
              </section>
            )}
          </section>
        </section>

        <Divider />

        <section className={style["game-comments"]}>
          <h2 className={style["game-comments-title"]}>
            <MessageOutlined />
            玩家评价
            <span className={style["comments-count"]}>
              （{comments.length}条）
            </span>
          </h2>

          {/* 评论列表 */}
          <div className={style["comments-list"]}>
            {comments.length > 0 ? (
              comments.map((comment: any) => (
                <div key={comment.id} className={style["comment-card"]}>
                  <div className={style["comment-header"]}>
                    <Avatar
                      className={style["comment-avatar"]}
                      src={comment.avatar}
                      icon={<UserOutlined />}
                    />
                    <span className={style["username"]}>
                      {comment.username}
                    </span>
                    <div className={style["comment-user"]}>
                      <Rate
                        disabled
                        defaultValue={comment.rating}
                        className={style["rating"]}
                        character={<StarFilled />}
                      />
                    </div>
                    <span className={style["comment-date"]}>
                      {timeAgo(comment.createdTime)}
                    </span>
                  </div>
                  <div className={style["comment-content"]}>
                    {comment.comment}
                  </div>
                </div>
              ))
            ) : (
              <div className={style["no-comments"]}>
                <Empty
                  description="暂无玩家评价，快来留下你的第一印象吧！"
                  imageStyle={{ height: 60 }}
                />
              </div>
            )}
          </div>
        </section>
      </div>
      <CommentButton
        type="game"
        rate={rate}
        setRate={setRate}
        comment={comment}
        setComment={setComment}
        commentCount={commentCount}
        addComment={addGameUserReview}
        currentUser={{
          username: profile.username,
          avatar: profile.avatar,
        }}
      />
    </div>
  );
}
